package com.cube.dp.base.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.lang.Nullable;

import javax.servlet.http.Cookie;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author poker.li
 * @date 2021/12/13 18:17:31
 */
public class CookieUtils {
    @Nullable
    public static Cookie[] getCurrentCookies() {
        return RequestUtils.currentCookies();
    }

    @Nullable
    public static Cookie get(String key) {
        if (key == null) {
            return null;
        }
        Cookie[] cookies = getCurrentCookies();
        if (ArrayUtil.isEmpty(cookies)) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie;
            }
        }
        return null;
    }

    @Nullable
    public static List<Cookie> getCookies(String key) {
        if (key == null) {
            return null;
        }
        Cookie[] cookies = getCurrentCookies();
        if (ArrayUtil.isEmpty(cookies)) {
            return null;
        }
        return Arrays.stream(cookies).filter(cookie -> key.equals(cookie.getName())).collect(Collectors.toList());
    }

    @Nullable
    public static String getValue(String key) {
        Cookie cookie = get(key);
        if (cookie == null) {
            return null;
        }
        return cookie.getValue();
    }

    @Nullable
    public static Map<String, String> cookieStringToMap(String stringCookie) {
        if (StrUtil.isBlank(stringCookie)) {
            return null;
        }
        String[] split = stringCookie.split(";");
        if (ArrayUtil.isEmpty(split)) {
            return null;
        }
        HashMap<String, String> map = new HashMap<>(16);
        for (String s : split) {
            if (StrUtil.isBlank(s)) {
                continue;
            }
            String[] split1 = s.split("=");
            if (ArrayUtil.isEmpty(split1) || split1.length == 1) {
                continue;
            }
            String key = split1[0];
            String value = split1[1];
            map.put(StrUtil.trim(key), value);
        }
        return map;
    }

}
